﻿<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Chat extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('form');
        $this->load->model('Jobs');
        $this->load->model('Chats');

        $user = & Users::getInstance();
        if ($user->id < 1) {
            // redirect to home
        }
    }

    function view() {
        $this->load->helper('url');
        $this->load->library('Menu');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        $jid = $this->uri->rsegment(3, 0);
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if ($user->level > 0) {
            $data['stats']['oncoming'] = $this->Jobs->getOncoming(-1, true);
            $data['stats']['quote'] = $this->Jobs->getNeedQuote(-1, true);

            $this->db->order_by("id", "DESC");
            $query = $this->db->get('docs');
            $data['docs'] = $query->result();
        }

        if (($data['job']->owner_id == $user->id) || ($user->level > 0)) {
            // set message to read for the viewing users group
            if ($user->level > 0) {
                $this->Jobs->setMessage($jid, 0, 1);
            } else {
                $this->Jobs->setMessage($jid, 0, 0);
            }

            $data['jobs'] = $this->Jobs->getOrderJobs($jid);
            $data['chat'] = $this->Chats->getConversation($jid);
            $data['owner'] = $user->getUserInfo($data['job']->owner_id);
            if ($user->id == 1) {
                $this->load->view('admin-chat', $data);
            } else {
                $this->load->view('chat', $data);
            }
        } else {
            // redirect to home
            redirect('/');
        }
    }

    function addcal() {
        $this->load->helper('url');
        $user = & Users::getInstance();

        if ($user->level > 0) {
            $jid = $this->uri->rsegment(3, 0);

            $this->Chats->addToCal($jid);

            $data = array(
                'cal' => 1,
            );

            $this->db->where('gid', $jid);
            $this->db->update('job_group', $data);
        }

        redirect('/joborder/' . $jid);
    }

    function cancelcal() {
        $this->load->helper('url');
        $user = & Users::getInstance();
        $jid = $this->uri->rsegment(3, 0);
        $this->Chats->cancelCal($jid);
        //redirect('/joborder/'.$jid);
    }

    function post() {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        $jid = $this->uri->rsegment(3, 0);
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if (($data['job']->owner_id == $user->id) || ($user->level > 0)) {
            $paid = 0;
            $paymentType = 0;
            if ($this->input->post('sendmessage')) {
                $text = $this->input->post('message');
                $type = 0;

                if ($user->level > 0) {
                    // user mail
                    $uinfo = $user->getUserInfo($data['job']->owner_id);
                    $mail = $uinfo->email;
                    $this->email->to($mail);
                    $this->email->from('ivy@bookabus.sg', 'Ivy');

                    $this->email->subject('Bookabus.sg – Message on Job Order #' . $this->Jobs->getID($data['job']));
                    $this->email->message('Message: ' . nl2br($text) . '
						<br /><br />
						To reply or take action, click ' . anchor('/joborder/' . $jid, 'here'));
                    $this->email->send();

                    $this->Jobs->setMessage($jid, 1, 0);
                } else {
                    // admin mail
                    $mail = $user->username;
                    $name = $user->name;
                    $this->email->reply_to($mail);
                    $this->email->from($mail, $name);
                    $this->email->to('daniel_champion1101@yahoo.com');

                    $this->email->subject('Bookabus.sg – Update on job #' . $this->Jobs->getID($data['job']));
                    $this->email->message('New message: ' . nl2br($text) . '
						<br /><br />
						To reply or take action, click ' . anchor('/joborder/' . $jid, 'here'));
                    $this->email->send();

                    /* ____send to developer______________________ */
                    $this->email->subject('Bookabus.sg - Developer Test - chat.php - line 135');
                    $this->email->to('hoang.dinh21@gmail.com');
                    $this->email->send();
                    /* __________________________________________ */

                    $this->Jobs->setMessage($jid, 1, 1);
                }
            } elseif ($this->input->post('sendquote')) {
                $price = $this->input->post('price');
                $tax = $this->input->post('tax');
                $discount = $this->input->post('discount');
                $pmethods = array();
                if ($this->input->post('paypal') == "1") {
                    $pmethods[] = 'paypal';
                }
                if ($this->input->post('bank') == "1") {
                    $pmethods[] = 'bank';
                }
                if ($this->input->post('cheque') == "1") {
                    $pmethods[] = 'cheque';
                }
                $pterms = 0;
                $pterms = $this->input->post('paymentterms');

                $preq = $this->input->post('preq');
                if ($preq < 0)
                    $preq = 0;

                $data['jobs'] = $this->Jobs->getOrderJobs($jid);

                foreach ($data['jobs'] as $route) {
                    $job_price = $this->input->post('pp' . $route->id);
                    $job_bus_type = $this->input->post('tt' . $route->id);

                    $this->Jobs->updateSingle($route->id, $job_price, $job_bus_type);
                }

                // Update job order's prices
                $this->Jobs->updatePrice($jid, $price, $tax, $discount, $preq, $this->input->post('terms'), json_encode($pmethods), 1, $pterms);
                $this->Jobs->setEndDate($jid, $this->input->post('duration'), $this->input->post('invalidafter'));
                $this->Jobs->setAdminMoreInfo($jid, $this->input->post('moreinfo'));

                $this->db->where("id", $this->input->post('terms'));
                $query = $this->db->get('docs');
                $tc = $query->row();

                // invoice
                $jsonFields = json_encode(array());
                $inv = $this->Jobs->addInvoice($jid, 0, $jsonFields, 1);

                /* $text = '<p>Here\'s our quote on the job order:</p>
                  <table>
                  <tr>
                  <td>Price, S$</td>
                  <td>'.$this->Jobs->formatPrice($price, false).'</td>
                  </tr>
                  <tr>
                  <td>'.$tax.'% Tax, S$</td>
                  <td>'.$this->Jobs->formatPrice($price * $tax/100, false).'</td>
                  </tr>
                  <tr>
                  <td>'.$discount.'% Discount, S$</td>
                  <td>'.$this->Jobs->formatPrice($price * $discount/100, false).'</td>
                  </tr>
                  <tr class="last-row">
                  <td>Total, S$</td>
                  <td>'.$this->Jobs->formatPrice(($price) + ($price * $tax/100) - ($price * $discount/100), false).'</td>
                  </tr>
                  </table>
                  <div class="clr"></div>
                  <p>You can view or print the quotation '.anchor('/invoices/view/'.$inv, 'here').'.
                  <p>'.anchor('/uploads/docs/'.$tc->file, 'Terms and conditions').'</p>
                  <p>This Offer will be valid until '.$this->input->post('invalidafter').'. It will become Invalid after that date.</p>'; */
                $text = '<p>Here\'s our quote on the job order:</p>
				<table>
					<tr>
						<td>Price, S$</td>
						<td>' . $this->Jobs->formatPrice($price, false) . '</td>
					</tr>
					<tr>
						<td>' . $tax . '% Tax, S$</td>
						<td>' . $this->Jobs->formatPrice($price * $tax / 100, false) . '</td>
					</tr>
					<tr>
						<td>' . $discount . '% Discount, S$</td>
						<td>' . $this->Jobs->formatPrice($price * $discount / 100, false) . '</td>
					</tr>
					<tr class="last-row">
						<td>Total, S$</td>
						<td>' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100), false) . '</td>
					</tr>
				</table>				
				<div class="clr"></div>
				' . (($this->input->post('moreinfo')) ? '<p>Additional info: ' . nl2br(htmlspecialchars($this->input->post('moreinfo'))) . '</p>' : '') . '
				<p>You can view or print the quotation ' . anchor('/invoices/view/' . $inv, 'here') . '.
				<p>' . anchor('/uploads/docs/' . $tc->file, 'Terms and conditions') . '</p>
                                <p>Job ID is used as Invoice number</p>
				<p>This Offer will be valid until ' . $this->input->post('invalidafter') . '. It will become Invalid after that date.</p>';
                $type = 1;
                //<p>Job ID is also used as your quotation reference</p>
                // send mail
                $uinfo = $user->getUserInfo($data['job']->owner_id);
                $groupId = $jid;
                $mail = $uinfo->email;
                $name = $uinfo->name;
                if (empty($name))
                    $name = "dear user";
                $untilDate = $this->input->post('invalidafter');

                $ji = $this->Jobs->getOrderJobs($groupId);
                $jobInfo = array();
                foreach ($ji as $route) {
                    $jobInfo[] = nl2br($this->Jobs->formatJobInfo($route));
                }

                $this->email->from('ivy@bookabus.sg', 'Ivy');
                $this->email->to($mail);

                $this->email->subject('Bookabus.sg – Quote on Job Order #' . $this->Jobs->getID($data['job']));

                // invoice
                $jsonFields = json_encode(array());
                $inv = $this->Jobs->addInvoice($groupId, 0, $jsonFields, 1);

                $this->email->message('Hello, ' . $name . ',
					<br /><br />
					We have submitted a quotation for job order #' . $this->Jobs->getID($data['job']) . ':
					<br /><br />
					' . implode("<br/>", $jobInfo) . '
					<br /><br />
					Price, S$: ' . $this->Jobs->formatPrice($price, false) . '
					<br />' . $tax . '% Tax, S$: ' . $this->Jobs->formatPrice($price * $tax / 100, false) . '
					<br />' . $discount . '% Discount, S$: ' . $this->Jobs->formatPrice($price * $discount / 100, false) . '
					<br />Total, S$: ' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100), false) . '
					<br />Payment in advance, S$: ' . $this->Jobs->formatPrice($preq, false) . '
					<br /><br />
					You can view or print the quotation ' . anchor('/invoices/view/' . $inv, 'here') . '<br/>
					' . anchor('/uploads/docs/' . $tc->file, 'Terms and conditions') . '
					<br /><br />
					Please have in mind that you can accept, deny or comment the offer until ' . $untilDate . '
					<br /><br />
					You can take action by going to ' . anchor('/joborder/' . $groupId, 'this page') . '
					<br /><br />
					Best Regards,
					<br />Ivy');
                $this->email->send();

                $this->Jobs->setMessage($jid, 1, 0);
            } elseif ($this->input->post('setcancelfee')) {
                $fee = $this->input->post('fee');

                $this->Jobs->setCancelFee($jid, $fee);
                if ($fee > 0) {
                    $jsonFields = json_encode(array());
                    $inv = $this->Jobs->addInvoice($jid, 2, $jsonFields, 0);

                    $text = '<p>According to the Terms and Conditions you have agreed to, you need to pay a cancelation fee of ' . $this->Jobs->formatPrice($fee) . '.</p><p>You can see the invoice ' . anchor('/invoices/view/' . $inv, 'here') . '</p>';

                    $type = 10;
                } else {
                    $text = 'This job order has been cancelled.';

                    $type = 7;
                }

                $this->Jobs->setMessage($jid, 1, 0);

                // send user mail
                $uinfo = $user->getUserInfo($data['job']->owner_id);
                $groupId = $jid;
                $mail = $uinfo->email;
                $name = $uinfo->name;
                if (empty($name))
                    $name = "dear user";

                $this->email->from('ivy@bookabus.sg', 'Ivy');
                $this->email->to($mail);

                $this->email->subject('Bookabus.sg – Cancellation on Job #' . $this->Jobs->getID($data['job']));
                $this->email->message('We have issued a new invoice on your order. You can see the invoice ' . anchor('/invoices/view/' . $inv, 'here') . '
					<br /><br />
					According to the Terms and Conditions you have agreed to, you need to pay a cancelation fee of ' . $this->Jobs->formatPrice($fee) . '.
					<br />You can see the invoice ' . anchor('/invoices/view/' . $inv, 'here') . '
					<br /><br />
					Best Regards,
					<br />Ivy');
                $this->email->send();
            } elseif ($this->input->post('sendpayment')) {
                $ptype = $this->input->post('payment');

                if (empty($ptype))
                    redirect('joborder/' . $jid);

                $j = $this->Jobs->getOrderJob($jid);

                if ($j->cancel == 1) { // cancellation payment
                    $price = $j->cancelfee;
                } else { // normal payment
                    /* $price = $this->input->post('price');

                      if (($price < $this->Jobs->neededPayment($jid)) || ($price > $this->Jobs->neededPayment($jid))) {
                      if ($price > ($j->price - $j->paid)) {
                      redirect('joborder/'.$jid);
                      }
                      } */
                    $price = $this->Jobs->neededPayment($jid);
                }

                if ($ptype == "paypal") {
                    // do paypal logic
                    require_once(FCPATH . "/paypal/paypal.php");
                    require_once(FCPATH . "/paypal/httprequest.php");

                    // Sandbox mode, new PayPal(true) for live
                    $r = new PayPal(true);

                    if ($j->cancel == 1) {
                        $payPalDescription = 'Bookabus cancellation fee for JOB ID: ' . $this->Jobs->getID($j);
                    } else {
                        if ($j->status < 4) {
                            $payPalDescription = 'Bookabus Payment for JOB ID: ' . $this->Jobs->getID($j);
                        } else {
                            $payPalDescription = 'Bookabus Advance Payment for JOB ID: ' . $this->Jobs->getID($j);
                        }
                    }

                    $ret = ($r->doExpressCheckout(site_url("/success.php?id=" . $jid), site_url("/cancel.php?id=" . $jid), $price, $payPalDescription));
                } else {
                    $refnum = $this->input->post('snumber');
                    $ptype = ($ptype == "cheque") ? "Cheque" : "Bank Transfer";
                    $paymentType = ($ptype == "cheque") ? 2 : 1;
                    $type = 5;
                    $paid = $price;

                    $text = '<p>I have sent the payment for ' . $this->Jobs->formatPrice($price) . ' via ' . $ptype . ' on ' . date("j M Y") . '.</p>';
                    $text .= '<p>Reference number: ' . $refnum . '</p>';

                    if ($j->cancel == 1) {
                        $this->Jobs->setCancelPaid($jid);
                    } else {
                        // update job status
                        if ($data['job']->status < 4) {
                            $this->Jobs->changeStatus($jid, 3);
                        } else {
                            $this->Jobs->changeStatus($jid, 6);
                        }
                    }

                    $mail = $user->username;
                    $name = $user->name;

                    // admin mail
                    $this->email->reply_to($mail);
                    $this->email->from($mail, $name);
                    $this->email->to('daniel_champion1101@yahoo.com');

                    $this->email->subject('Bookabus.sg – Update on job #' . $this->Jobs->getID($data['job']));
                    $this->email->message('I have sent the payment for ' . $this->Jobs->formatPrice($price) . ' via ' . $ptype . ' on ' . date("j M Y") . '
						<br /><br />
						To reply or take action, click ' . anchor('/joborder/' . $jid, 'here'));
                    $this->email->send();

                    /* ____send to developer______________________ */
                    $this->email->subject('Bookabus.sg - Developer Test - chat.php - line 379');
                    $this->email->to('hoang.dinh21@gmail.com');
                    $this->email->send();
                    /* __________________________________________ */
                    $this->Jobs->setMessage($jid, 1, 1);
                }
            } elseif ($this->input->post('changeprice')) {
                $priceR = $this->input->post('amount');
                if ($priceR{0} == "-") {
                    $priceP = $priceR;
                    $priceS = "DECREASED";
                } else {
                    if ($priceR{0} == "+") {
                        $priceP = $priceR;
                    } else {
                        $priceP = "+" . $priceR;
                    }
                    $priceS = "INCREASED";
                }

                $this->Jobs->changePrice($jid, $this->input->post('reason'), $priceP);

                $text = '<p>We have provided a new quote for your job.</p>'
                        . '<p>We have ' . $priceS . ' the price by ' . $this->Jobs->formatPrice(str_replace(array('-', '+'), '', $this->input->post('amount'))) . ' because of the following fact:</p><p>' . $this->input->post('reason') . '</p>';
                $type = 8;

                $this->Jobs->setMessage($jid, 1, 0);

                $this->email->from('ivy@bookabus.sg', 'Ivy');
                $uinfo = $user->getUserInfo($data['job']->owner_id);
                $mail = $uinfo->email;
                $this->email->to($mail);

                $this->email->subject('Bookabus.sg – We have provided a new quote for your job #' . $this->Jobs->getID($data['job']));
                $jobinfo = $this->Jobs->getPrice($jid);
                $jsonFields = json_encode(array());
                $inv = $this->Jobs->addInvoice($jid, 0, $jsonFields, 1);

                $query = $this->db->get('docs');
                $tc = $query->row();

                $text = $text . '<p>Here\'s our quote on the job order:</p>
				<table>
					<tr>
						<td>Price, S$</td>
						<td>' . $this->Jobs->formatPrice($jobinfo->price, false) . '</td>
					</tr>
					<tr>
						<td>' . $jobinfo->tax . '% Tax, S$</td>
						<td>' . $this->Jobs->formatPrice(($jobinfo->price * $jobinfo->tax) / 100, false) . '</td>
					</tr>
					<tr>
						<td>' . $jobinfo->discount . '% Discount, S$</td>
						<td>' . $this->Jobs->formatPrice(($jobinfo->price * $jobinfo->discount) / 100, false) . '</td>
					</tr>
					<tr class="last-row">
						<td>Total, S$</td>
						<td>' . $this->Jobs->formatPrice($jobinfo->price + (($jobinfo->price * $jobinfo->tax) / 100) - (($jobinfo->price * $jobinfo->discount) / 100), false) . '</td>
					</tr>
				</table>				
				<div class="clr"></div>'
                        . (($jobinfo->moreinfo) ? '<p>Additional info: ' . nl2br(htmlspecialchars($jobinfo->moreinfo)) . '</p>' : '')
                        . '<p>You can view or print the quotation ' . anchor('/invoices/view/' . $inv, 'here') .
                        '<p>' . anchor('/uploads/docs/' . $tc->file, 'Terms and conditions') . '</p>
                                <p>Job ID is used as Invoice number</p>
				<p>This Offer will be valid until ' . $jobinfo->invalid . '. It will become Invalid after that date.</p>';

                $this->email->message($text . '<br/>Best Regards,<br />Ivy');
                $this->email->send();

                /* ____send to developer______________________ */
                $this->email->subject('Bookabus.sg - Developer Test - chat.php - line 416');
                $this->email->to('hoang.dinh21@gmail.com');
                $this->email->send();
                /* __________________________________________ */
            }

            $this->Chats->post($jid, $user->id, $text, $type, $paid, $paymentType);

            redirect('joborder/' . $jid);
        } else {
            // redirect to home
            redirect('');
        }
    }

    function paypal($jid, $token, $pid) {
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $user = & Users::getInstance();
        $data['job'] = $this->Jobs->getOrderJob($jid);

        require_once(FCPATH . "/paypal/paypal.php");
        require_once(FCPATH . "/paypal/httprequest.php");

        // Sandbox mode, new PayPal(true) for live
        $r = new PayPal(true);

        $final = $r->doPayment($pid, $token);

        if ($final['ACK'] == 'Success') {
            if ($data['job']->cancelfee > 0) {
                $this->Jobs->changeStatus($jid, 8);

                $this->Chats->post($jid, 0, '<p>The job order is now cancelled.</p>', 7);
            } else {
                $price = $final['AMT'];
                $paymentType = 0;
                $text = '<p>I have sent the payment for ' . $this->Jobs->formatPrice($price) . ' via PayPal on ' . date("j M Y") . '.</p>';
                $type = 5;
                $paid = $price;

                $this->Jobs->addPayment($jid, $price);
                $ppPrice = $price;

                $this->Chats->post($jid, $user->id, $text, $type, $paid, $paymentType);

                // update job status
                /*
                  if ($data['job']->status < 4) {
                  $this->Jobs->changeStatus($jid, 4);
                  } else {
                  $this->Chats->post($jid, 0, '<p>Job order is now successfully finished and closed.</p>', 7);
                  $this->Jobs->changeStatus($jid, 7);
                  }
                 */
                // if paid with paypal, auto move to job order successfully
                $this->Chats->post($jid, 0, '<p>Job order is now successfully completed.</p>', 7);
                if ($this->Jobs->neededPayment($jid) > 0) {
                    $this->Jobs->changeStatus($jid, 14);
                } else {
                    $this->Jobs->changeStatus($jid, 13);
                }

                // send mail
                $mail = $user->username;
                $name = $user->name;

                $this->email->from('ivy@bookabus.sg', 'Ivy');
                $this->email->to($mail);

                $price = $data['job']->price;
                $tax = $data['job']->tax;
                $discount = $data['job']->discount;
                $preq = $data['job']->preq;

                $jsonFields = json_encode(array());
                $inv = $this->Jobs->addInvoice($jid, 0, $jsonFields, 1);

                $this->email->subject('Bookabus.sg – Payment for Job Order #' . $this->Jobs->getID($data['job']));
                $this->email->message('Hello, ' . $name . ',
					<br /><br />
					We have received a payment from you for Job Order #' . $this->Jobs->getID($data['job']) . '.
					<br /><br />
					Total Price: SGD ' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100), false) . '
					<br />Paid: SGD ' . $this->Jobs->formatPrice($ppPrice, false) . '
					<br />Balance: SGD -' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100) - $ppPrice, false) . '
					<br /><br />
					You can view or print the quotation ' . anchor('/invoices/view/' . $inv, 'here') .
                        '<br/>Best Regards,
					<br />Ivy');
                $this->email->send();

                // admin mail
                $this->email->reply_to($mail);
                $this->email->from($mail, $name);
                $this->email->to('daniel_champion1101@yahoo.com');

                $this->email->subject('Bookabus.sg – Update on job #' . $this->Jobs->getID($data['job']));
                $this->email->message('I have sent the payment via PayPal on ' . date("j M Y") . '
					<br /><br />
					Total Price: SGD ' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100), false) . '
					<br />Paid: SGD ' . $this->Jobs->formatPrice($ppPrice, false) . '
					<br />Balance: SGD -' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100) - $ppPrice, false) . '
					<br /><br />
					To reply or take action, click ' . anchor('/joborder/' . $jid, 'here'));
                $this->email->send();

                /* ____send to developer______________________ */
                $this->email->subject('Bookabus.sg - Developer Test - chat.php - line 501');
                $this->email->to('hoang.dinh21@gmail.com');
                $this->email->send();
                /* __________________________________________ */

                $this->Jobs->setMessage($jid, 1, 1);
            }
        }

        redirect('/joborder/' . $jid);
    }

    function accept() {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        $jid = $this->uri->rsegment(3, 0);
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if ($data['job']->owner_id == $user->id) {
            $userMessage = ($this->input->post('acceptDenyMsg')) ? "<br />" . nl2br(htmlspecialchars($this->input->post('acceptDenyMsg'))) : "";

            $this->Chats->post($jid, $user->id, 'I accept your offer.' . $userMessage, 2);
            if ($data['job']->preq > 0) {
                $this->Jobs->changeStatus($jid, 2);
            } else {
                //$this->Jobs->changeStatus($jid, 4);
                $this->Jobs->changeStatus($jid, 2);
            }

            // send mail
            $mail = $user->username;
            $name = $user->name;

            $this->email->from('ivy@bookabus.sg', 'Ivy');
            $this->email->to($mail);

            $price = $data['job']->price;
            $tax = $data['job']->tax;
            $discount = $data['job']->discount;
            $preq = $data['job']->preq;

            /* $pmethods = json_decode($data['job']->pmethods);
              $pmText = array();
              foreach ($pmethods as $pm) {
              if ($pm == "paypal") $pmText[] = "PayPal";
              if ($pm == "bank") $pmText[] = "Bank Transfer";
              if ($pm == "cheque") $pmText[] = "Cheque";
              }
              $pmTexts = implode(", ", $pmText); */

            $this->email->subject('Bookabus.sg – Quote on Job #' . $this->Jobs->getID($data['job']) . ' Accepted!');
            $this->email->message('Hello, ' . $name . ',
				<br /><br />
				We are happy that you have accepted our offer for Job Order #' . $this->Jobs->getID($data['job']) . '
				<br /><br />
				Total Price: SGD ' . $this->Jobs->formatPrice(($price) + ($price * $tax / 100) - ($price * $discount / 100), false) . '
				<br />Due in advance: SGD ' . $this->Jobs->formatPrice($preq, false) . '
				<br /><br />
				
				Best Regards,
				<br />Ivy');
            $this->email->send();
            /* _________You can pay the due amount, if any, via '.$pmTexts.' by clicking '.anchor('/joborder/'.$jid, 'here').'.
              <br /><br />________ */
            // admin mail
            $this->email->reply_to($mail);
            $this->email->from($mail, $name);
            $this->email->to('daniel_champion1101@yahoo.com

            $this->email->subject('Bookabus.sg – Update on job #' . $this->Jobs->getID($data['job']));
            $this->email->message('Offer accepted
				<br /><br />
				To reply or take action, click ' . anchor('/joborder/' . $jid, 'here'));
            $this->email->send();

            /* ____send to developer______________________ */
            $this->email->subject('Bookabus.sg - Developer Test - chat.php - line 588');
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->send();
            /* __________________________________________ */

            $this->Jobs->setMessage($jid, 1, 1);
        }

        redirect('');
    }

    function deny() {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        $jid = $this->uri->rsegment(3, 0);
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if (($data['job']->owner_id == $user->id) || ($user->id == 1)) {
            // 0 - cancel, 1 - deny
            if ($data['job']->status == 0) {
                $this->Chats->post($jid, $user->id, 'I cancelled the job order.', 0);
                $this->Jobs->changeStatus($jid, 8);
            } elseif ($data['job']->status == 1) {
                $userMessage = ($this->input->post('acceptDenyMsg')) ? "<br />" . nl2br(htmlspecialchars($this->input->post('acceptDenyMsg'))) : "";

                $this->Chats->post($jid, $user->id, 'I denied your offer.' . $userMessage, 0);
                $this->Jobs->changeStatus($jid, 8);
            }
        }



        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);
        $reason = $this->input->get('reason');
        $menu = new Menu;
        $user = & Users::getInstance();
        $email = $user->username;
        $sname = $user->name;

        $data = $menu->gen();
        $data['user'] = $user;
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if (($data['job']->owner_id == $user->id) || ($user->id == 1)) {
            $uinfo = $user->getUserInfo($data['job']->owner_id);
            $mail = $uinfo->email;
            $name = $uinfo->name;

            // mail to user
            $this->email->from('ivy@bookabus.sg', 'Ivy');
            $this->email->to($mail);

            $this->email->subject('Bookabus.sg – Decline Job');

            $this->email->message('This job (#' . $jid . ' ) has been declined due to: ' . $reason);

            $this->Chats->post($jid, 0, '<p>I have declined this job due to: ' . $reason . '.</p>', 7);
            $this->email->send();

            /* ____send to developer______________________ */
            $this->email->subject('Bookabus.sg - Decline Job');
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->send();
            /* __________________________________________ */
        }




        /* $this->Chats->cancelCal($jid);
          //redirect('joborder/'.$jid); */
        redirect('');
    }

    function receive() {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        $jid = $this->uri->rsegment(3, 0);
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if ($user->level > 0) {
            if ($data['job']->cancelfeepaid == 1) {
                $this->Jobs->changeStatus($jid, 8);

                $this->Chats->post($jid, 0, '<p>The job order is now cancelled.</p>', 7);
            } else {
                $price = $this->Chats->getSentPrice($jid);

                if ($price->paid > 0) {
                    $pPrice = $price->paid;
                    // invoice
                    /* $idata = array(
                      'jid' => $jid,
                      'type' => 0,
                      'date' => date('Y-m-d')
                      );

                      $this->db->insert('ainvoices', $idata);
                      $inv = $this->db->insert_id(); */
                    //$jsonFields = json_encode(array());
                    //$inv = $this->Jobs->addInvoice($jid, 0, $jsonFields, 1);

                    $text = '<p>We have received your payment for ' . $this->Jobs->formatPrice($price->paid) . ' via ' . constant("CHAT_PAYMENT_" . $price->payment) . ' on ' . date("j M Y") . '.</p>';
                    //<p>You can '.anchor('/invoices/view/'.$inv, 'access your invoice').' for the amount.</p>';
                    // send mail
                    $uinfo = $user->getUserInfo($data['job']->owner_id);
                    $mail = $uinfo->email;
                    $name = $uinfo->name;

                    $this->email->from('ivy@bookabus.sg', 'Ivy');
                    $this->email->to($mail);

                    $aPrice = $data['job']->price;
                    $tax = $data['job']->tax;
                    $discount = $data['job']->discount;
                    $preq = $data['job']->preq;

                    $jsonFields = json_encode(array());
                    $inv = $this->Jobs->addInvoice($jid, 0, $jsonFields, 1);

                    $this->email->subject('Bookabus.sg – Payment for Job #' . $this->Jobs->getID($data['job']));
                    $this->email->message('Hello, ' . $name . ',
						<br /><br />
						We have received a payment from you for Job Order #' . $this->Jobs->getID($data['job']) . '.
						<br /><br />
						Total Price: SGD ' . $this->Jobs->formatPrice(($aPrice) + ($aPrice * $tax / 100) - ($aPrice * $discount / 100), false) . '
						<br />Paid: SGD ' . $this->Jobs->formatPrice($pPrice, false) . '
						<br />Balance: SGD -' . $this->Jobs->formatPrice(($aPrice) + ($aPrice * $tax / 100) - ($aPrice * $discount / 100) - $pPrice, false) . '
						<br /><br />
						You can view or print the quotation ' . anchor('/invoices/view/' . $inv, 'here') .
                            'Best Regards,
						<br />Ivy');
                    $this->email->send();

                    $jobinfo = $this->db->get_where('job_group', array('gid' => $jid, 'cal' => 0));
                    $jobinfo = $jobinfo->result();
                    if (count($jobinfo) > 0) {
                        $this->Chats->addToCal($jid);

                        $cdata = array(
                            'cal' => 1,
                        );

                        $this->db->where('gid', $jid);
                        $this->db->update('job_group', $cdata);
                    }

                    $this->Chats->post($jid, $user->id, $text, 5);

                    // update price paid
                    $this->Jobs->addPayment($jid, $price->paid);
                    if ($data['job']->status < 5) {
                        $this->Jobs->changeStatus($jid, 4);
                    } else {
                        //$this->Chats->post($jid, $user->id, '<p>Job order is now successfully finished and closed.</p>', 7);
                        //$this->Jobs->changeStatus($jid, 7);
                        $this->Chats->post($jid, $user->id, '<p>Job order is now successfully completed.</p>', 7);
                        if ($this->Jobs->neededPayment($jid) > 0) {
                            $this->Jobs->changeStatus($jid, 14);
                        } else {
                            $this->Jobs->changeStatus($jid, 13);
                        }
                    }

                    $this->Jobs->setMessage($jid, 1, 0);
                }
            }
        }

        redirect('joborder/' . $jid);
    }

    function delete($jid) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;

        if ($user->level > 0) {
            $this->Chats->post($jid, $user->id, 'Order deleted by admin.', 0);
            $this->Jobs->changeStatus($jid, 11);
        }

        // send email when delete job order
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);
        $job = $this->Jobs->getOrderJob($jid);
        $jobid = $this->Jobs->getID($job->gid);
        if ($user->level > 0) {
            $userinfo = $this->Users->getUserInfo($job->owner_id);
            $email = $userinfo->email;
            $name = $userinfo->name;
        } else {
            $email = $user->username;
            $name = $user->name;
        }

        $subject = 'Bookabus.sg – Job Order #' . $this->Jobs->getID($job->gid) . ' Deleted!';

        //send to customer
        $this->email->from('ivy@bookabus.sg', 'Ivy');
        $this->email->to($email);
        $this->email->subject($subject);
        $mmessage = 'Hello, ' . $name . ',
					<br /><br />
					You have successfully deleted the job order #' . $jobid . '.<br />
					Best Regards,
					<br />Ivy';
        $this->email->message($mmessage);
        $this->email->send();

        /* ____send to developer______________________ */
        $this->email->subject('Bookabus.sg - Job #' . $jobid . ' is deleted - request.php - line 903 - ' . $email . '-' . $job->owner_id);
        $this->email->to('hoang.dinh21@gmail.com');
        $this->email->send();
        /* __________________________________________ */

        // send to admin
        $this->email->from('book@bookabus.sg', 'Admin');
        $this->email->to('daniel_champion1101@yahoo.com');

        $mmessage = 'The job order #' . $jobid . ' is deleted.';
        $this->email->message($mmessage);
        $this->email->send();
        //redirect('joborder/'.$jid);
        redirect('');
    }

    /* __________________________Luan's code____________________________ */

    function payment($jid) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;

        if ($user->level > 0) {
            $this->Chats->post($jid, $user->id, 'Payment is available now.', 0);
            $this->Jobs->changeStatus($jid, 4);
        }

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);
        $reason = $this->input->get('purpose');
        $menu = new Menu;
        $user = & Users::getInstance();
        $email = $user->username;
        $sname = $user->name;

        $data = $menu->gen();
        $data['user'] = $user;
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if (($data['job']->owner_id == $user->id) || ($user->id == 1)) {
            $uinfo = $user->getUserInfo($data['job']->owner_id);
            $mail = $uinfo->email;
            $name = $uinfo->name;

            // mail to user
            $this->email->from('ivy@bookabus.sg', 'Ivy');
            $this->email->to($mail);

            $this->email->subject('Bookabus.sg – Accept payment');

            $this->email->message('This job (#' . $jid . ' ) has been accepted for payment with purpose: ' . $reason);


            $this->email->send();

            /* ____send to developer______________________ */
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->send();
            /* __________________________________________ */
        }
        //redirect('joborder/'.$jid);
        redirect('');
    }

    function receive_payment($jid) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;

        if ($user->level > 0) {
            $this->Chats->post($jid, $user->id, 'I have received your payment', 0);
            $this->Jobs->changeStatus($jid, 7);
        }

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);
        $menu = new Menu;
        $user = & Users::getInstance();
        $email = $user->username;
        $sname = $user->name;

        $data = $menu->gen();
        $data['user'] = $user;
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if (($data['job']->owner_id == $user->id) || ($user->id == 1)) {
            $uinfo = $user->getUserInfo($data['job']->owner_id);
            $mail = $uinfo->email;
            $name = $uinfo->name;

            // mail to user
            $this->email->from('ivy@bookabus.sg', 'Ivy');
            $this->email->to($mail);

            $this->email->subject('Bookabus.sg – Received payment');

            $this->email->message('I have received payment from you for this job (#' . $jid . ' )');


            $this->email->send();

            /* ____send to developer______________________ */
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->send();
            /* __________________________________________ */
        }
        //redirect('joborder/'.$jid);
        redirect('');
    }

    /* _________________________End Luan's code_________________ */

    function cancel($jid = 0) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $menu = new Menu;
        $user = & Users::getInstance();
        $email = $user->username;
        $name = $user->name;

        $data = $menu->gen();
        $data['user'] = $user;
        $data['job'] = $this->Jobs->getOrderJob($jid);

        if ($data['job']->owner_id == $user->id) {
            //_______________________________________________________
            $msql = "SELECT * FROM `job_group` WHERE `gid` = " . $jid;
            $mquery = $this->db->query($msql);
            $mjob = $mquery->row();
            $today = time();
            $pa = strtotime($mjob->start_date) - $today;
            //_______________________________________________________
            // admin mail
            $this->email->reply_to($email);
            $this->email->from($email, $name);
            $this->email->to('daniel_champion1101@yahoo.com');

            $this->email->subject('Bookabus.sg – Update on job #' . $this->Jobs->getID($data['job']));

            if ($pa < 86400) {
                $this->email->message('I want to cancel the job.
				<br /><br />
				To reply or take action, click ' . anchor('/joborder/' . $jid, 'here'));
            } else {
                $this->email->message('I cancel the job.
				<br /><br />
				To take action, click ' . anchor('/joborder/' . $jid, 'here'));
            }

            $this->email->send();

            /* ____send to developer______________________ */
            $this->email->subject('Bookabus.sg - Developer Test - chat.php - line 780');
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->send();
            /* __________________________________________ */

            if ($pa < 86400) {
                $this->Chats->post($jid, $user->id, 'I want to cancel this job order.', 0);
            }else
                $this->Chats->post($jid, $user->id, 'I cancel this job order.', 0);
            $this->Jobs->cancelOrder($jid);
            $this->Jobs->setMessage($jid, 1, 1);
        }
        $this->Chats->cancelCal($jid);
        redirect('joborder/' . $jid);
    }

}

/* End of file request.php */
/* Location: ./application/controllers/request.php */